package com.midian.common.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by tech-010 on 2016/11/3.
 */
public class HtmlTools {
    /**
     * 将所有的html标签去掉以免影响格式
     *
     * @param content
     * @param contentMaxLength 最大文章文本显示长度
     * @return
     */
    public static String deleteHtmlFromContent(String content, int contentMaxLength) {
        String htmlRegxp = "<([^>]*)>";//html正则
        StringBuffer sb = new StringBuffer();
        //将所有的html标签去掉以免影响格式
        Matcher matcher = Pattern.compile(htmlRegxp).matcher(content);
        while (matcher.find()) {
            matcher.appendReplacement(sb, "");
        }
        matcher.appendTail(sb);
        content = sb.toString().replace("&nbsp;", "").trim();
        if (content.length() > contentMaxLength)
            content = content.substring(0, contentMaxLength) + "...";
        return content;
    }

    public static List<String> sepImgWithCount(String content, int count, boolean isWhenNonAddDefault) {
        String ImgRegxp = "<\\s*img\\s+([^>]*)\\s*>";//img正则
        //选出文本中第一个图片，没有则使用碧诗莱商标
        Matcher matcher = Pattern.compile(ImgRegxp).matcher(content);
        List<String> re = new ArrayList<String>();
        while (count > 0 && matcher.find()) {
            re.add(matcher.group());
            count--;
        }
        if (isWhenNonAddDefault && re.size() == 0)
            re.add("<img src='/bishilai.ico' />");
        return re;
    }

    public static List<String> getImgStrNonDefault(String htmlStr) {
        List<String> re = getImgStr(htmlStr);
        if (re.size() == 0)
            re.add("/images/placeholder.jpg");
        return re;
    }

    public static List<String> getImgStr(String htmlStr) {
        String img = "";
        Pattern p_image;
        Matcher m_image;
        List<String> pics = new ArrayList<String>();

        //     String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址

        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile
                (regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            img = img + "," + m_image.group();
            // Matcher m  = Pattern.compile("src=\"?(.*?)(\"|>|\\s+)").matcher(img); //匹配src

            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);

            while (m.find()) {
                pics.add(m.group(1));
            }
        }

        return pics;
    }
}
